package com.gaussic.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/3/31 0031.
 */
public class LogFilter implements Filter {
    FilterConfig config;

    public void destroy() {
        this.config = null;
    }

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // 获取ServletContext 对象，用于记录日志
        ServletContext context = this.config.getServletContext();
        //long before = System.currentTimeMillis();
        System.out.println("before the log filter!");
        //context.log("开始过滤");
        // 将请求转换成HttpServletRequest 请求
        HttpServletRequest hreq = (HttpServletRequest) req;
        // 记录日志
        System.out.println("Log Filter已经截获到用户的请求的地址:"+hreq.getServletPath() );
        //context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());
        try {
            // Filter 只是链式处理，请求依然转发到目的地址。
            chain.doFilter(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("after the log filter!");

    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("begin do the log filter!");
        this.config = config;

        //得到过滤器的名字
        String filterName = config.getFilterName();
        //得到在web.xml文件中配置的初始化参数
        String initParam1 = config.getInitParameter("name");
        String initParam2 = config.getInitParameter("like");
        //返回过滤器的所有初始化参数的名字的枚举集合。
        Enumeration<String> initParameterNames = config.getInitParameterNames();

        System.out.println(filterName);
        System.out.println(initParam1);
        System.out.println(initParam2);
        while (initParameterNames.hasMoreElements()) {
            String paramName = (String) initParameterNames.nextElement();
            System.out.println(paramName);
        }
        System.out.println("begin do the log filter end!");
    }

}